package com.ebt.m.users;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.users.bean.CardHonour;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.utils.EbtUtils;
import com.ebt.m.utils.PhotoCaptureUtil;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.view.CircleImageView;
import com.ebt.m.widget.MDEBTDialog;

import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by wanglu on 2018/2/7.
 */

public class CardHonourEditActivity extends BaseToolBarActivity {
    @BindView(R.id.honour_img)
    CircleImageView honourImg;
    @BindView(R.id.iv_arrow)
    ImageView ivArrow;
    @BindView(R.id.img_container)
    RelativeLayout imgContainer;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.honour_title)
    EditText honourTitle;
    @BindView(R.id.honour_date)
    TextView honourDate;
    @BindView(R.id.arrow)
    ImageView arrow;
    @BindView(R.id.honour_description)
    EditText honourDescription;
    @BindView(R.id.tips)
    TextView tips;
    @BindView(R.id.action_save)
    Button actionSave;
    @BindView(R.id.item_root)
    LinearLayout itemRoot;
    @BindView(R.id.date_container)
    RelativeLayout dateContainer;
    private EBTProgressDialog mProgressDialog;
    private CardHonour mCardHonour;
    private int mode;// 0  添加 ；  1  编辑
    private PhotoCaptureUtil mPhotoCaptureUtil;
    private String newPortraitPath = "";
    public static final int MODE_ADD = 0;
    public static final int MODE_EDIT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_carddata_edit_honour);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
        ButterKnife.bind(this);
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.containsKey("honour")) {
            mCardHonour = (CardHonour) getIntent().getExtras().getSerializable("honour");
            mode = 1;
            setTitle("编辑个人荣誉");
        } else {
            mode = 0;
            setTitle("添加个人荣誉");
            mCardHonour = new CardHonour();
        }
        initView();

    }

    private void initView() {
        initProgressDialog();
        if (mode == MODE_EDIT) {
            Glide.with(this)
                    .load(mCardHonour.getImgAddress())
                    .error(R.drawable.empty_photo)
                    .dontAnimate()
                    .into(honourImg);
            honourTitle.setText(mCardHonour.getTitle());
            honourDate.setText(mCardHonour.getDate());
            honourDescription.setText(mCardHonour.getDescription());
            tips.setText("还可输入" + (50 - mCardHonour.getDescription().length()) + "个字");
        }
        honourDescription.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                long length = 50 - s.toString().length();
                tips.setText("还可输入" + (length) + "个字");
            }
        });

    }


    private void initProgressDialog() {
        mProgressDialog = new EBTProgressDialog(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


    @OnClick({R.id.img_container, R.id.date_container, R.id.action_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_container:
                toSelectPhoto();
                break;
            case R.id.date_container:
                toSelectDate();
                break;
            case R.id.action_save:
                toSaveHonour();
                break;
        }
    }

    private void toSaveHonour() {
        String newDescription = honourDescription.getText().toString().trim();
        String newTitle = honourTitle.getText().toString().trim();
        String newDate = honourDate.getText().toString().trim();
        if (checkValues(newDate, newDescription, newTitle)) {
            mProgressDialog.show();
            EBTAPI ebtapi = AppInitService.getEbtApi();
            Observable.just(newPortraitPath)
                    .flatMap(path -> {
                        if (TextUtils.isEmpty(path)) {
                            return Observable.just("");
                        } else {
                            MultipartBody.Part file = generateMultipartBody("file", newPortraitPath);
                            UserInfo userInfo = AppContext.getCurrentUser();
                            String agentId = userInfo.getUserId()+"/";
                            return ebtapi.updateFile(file, "", ConfigData.CARD_PORTRAIT_BUCKET, ConfigData.CARD_PORTRAIT_DISK_PATH+agentId)
                                    .map(resultFile -> {
                                        if (resultFile != null && resultFile.data != null && !TextUtils.isEmpty(resultFile.data.getDownLoadUrl())) {
                                            return resultFile.data.getDownLoadUrl();
                                        } else {
                                            return "";
                                        }
                                    });
                        }
                    })
                    .flatMap(newPortraitPath -> {
                        mCardHonour.setTitle(newTitle);
                        mCardHonour.setDescription(newDescription);
                        mCardHonour.setDate(newDate);
                        mCardHonour.setImgAddress(TextUtils.isEmpty(newPortraitPath) ? mCardHonour.getImgAddress() : newPortraitPath);
                        return ebtapi.saveHonour(mCardHonour)
                                .map(result -> {
                                    try {
                                        JSONObject jsonObject = new JSONObject(result.body().string());
                                        long num = jsonObject.getJSONObject("data").getLong("attachmentId");
                                        return num;
                                    } catch (Exception e) {
                                        return Long.valueOf(0);
                                    }
                                });
                    })
                    .compose(RxUtil.rxTransformer(this))
                    .subscribe(num -> {
                        mProgressDialog.dismiss();
                        if (num == 0) {
                            ToastUtil.show(this, mode == MODE_EDIT ? "编辑荣誉失败" : "添加荣誉失败");
                        } else {
                            ToastUtil.show(this, mode == MODE_EDIT ? "编辑荣誉成功" : "添加荣誉成功");
                            finish();
                        }
                    }, throwable -> {
                        mProgressDialog.dismiss();
                        NetUtils.checkHttpException(this, throwable);
                        throwable.printStackTrace();
                    });
        }

    }

    public MultipartBody.Part generateMultipartBody(String name, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            return null;
        }
        RequestBody requestFileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath));
        return MultipartBody.Part.createFormData(name, uploadFile.getName(), requestFileBody);
    }

    private boolean checkValues(String newDate, String newDescription, String newTitle) {
        if (mode == MODE_ADD && TextUtils.isEmpty(newPortraitPath)) {
            ToastUtil.show(this, "图片不得为空");
            return false;
        } else if (mode == MODE_EDIT && TextUtils.isEmpty(newPortraitPath) && TextUtils.isEmpty(mCardHonour.getImgAddress())) {
            ToastUtil.show(this, "图片不得为空");
            return false;
        }
        if (TextUtils.isEmpty(newTitle)) {
            ToastUtil.show(this, "荣誉名称不得为空");
            return false;
        }
        if (TextUtils.isEmpty(newDate)) {
            ToastUtil.show(this, "荣誉时间不得为空");
            return false;
        }
        if (TextUtils.isEmpty(newDescription)) {
            ToastUtil.show(this, "荣誉描述不得为空");
            return false;
        }
        return true;
    }

    /**
     * 选择照片
     */
    private void toSelectPhoto() {
        String tmpPath = EbtUtils.getCompletePortraitPath();//指定存放路径
        mPhotoCaptureUtil = new PhotoCaptureUtil(this);
        mPhotoCaptureUtil.setFrom(true);
        mPhotoCaptureUtil.setOnPhotoCaptureListener(new PhotoCaptureUtil.OnPhotoCaptureListener() {
            @Override
            public void onPhotoCaptured(final String path) {
                if (TextUtils.isEmpty(path)) {
                    return;
                }

                Glide.with(CardHonourEditActivity.this)
                        .load(new File(path))
                        .error(R.drawable.empty_photo)
                        .dontAnimate()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .listener(new RequestListener<File, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, File model, Target<GlideDrawable> target, boolean isFirstResource) {
                                e.printStackTrace();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, File model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                return false;
                            }
                        })
                        .into(honourImg);
                newPortraitPath = path;
            }
        });
        String[] messages = new String[]{"相册", "拍照"};
        new MDEBTDialog.Builder(this)
                .setMessages(messages)
                .setTitle("选择图片")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                    @Override
                    public void onItemClicked(int index) {
                        if (index == 0) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_ALBUM,
                                    255, 189, tmpPath);
                        } else if (index == 1) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_CAMERA,
                                    255, 189, tmpPath);
                        }
                    }
                })
                .setShowPositiveButton(false)
                .create()
                .show();
    }

    private void toSelectDate() {
        Calendar c = Calendar.getInstance(Locale.getDefault());
        c.setTimeInMillis(AppContext.getCurrentTime());

        PickerHelper.chooseBirthday(this, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar c = Calendar.getInstance(Locale.getDefault());
                c.set(year, month, dayOfMonth);
                Date d = c.getTime();
                if (TimeUtils.compareToday(d) > 0) {
                    UIHelper.makeToast(CardHonourEditActivity.this, "日期不能晚于当天");
                    return;
                }
                String newDate = DateUtils.dateTime2String(d, "yyyy-MM-dd");
                honourDate.setText(newDate);
            }
        });
    }
}
